import { ISingleton } from "./ISingleton";
import { ResLoadMgr } from "./ResLoadMgr";


const {ccclass, property} = cc._decorator;

export class BundleResInfo {
    constructor(resPath: string) {
        this.path = resPath;
        this.bundleName = 'resources';
    }

    path: string;
    bundleName: string;
}

@ccclass
export  class CommonUtils extends ISingleton{

    public async sleepTime(time: number, target?) {
        return new Promise<void>((resolve, reject) => {
            if (target) {
                target.scheduleOnce(resolve, time / 1000);
            } else {
                setTimeout(resolve, time);
            }
        });
    }

    // 动态加载图片
    public async getSpriteFrame(name: string): Promise<cc.SpriteFrame> {
        return ResLoadMgr.Instance.loadBundleRes('resources', name, cc.SpriteFrame);
    }

    // 动态加载预制体
    public async openPrefab(path:string){
        const prefab: cc.Prefab = await ResLoadMgr.Instance.loadBundleRes('resources', path, cc.Prefab);
        return cc.instantiate(prefab);
    }

    // 播放音效
    public async playMusicByResPath(path: string, bundleName?: string, loop = true): Promise<void> {
        const bgm = await this.getAudioClip(path, bundleName);
        if (!bgm) {
            return;
        }
        cc.audioEngine.playMusic(bgm, loop);
    }

     /**
     * 通过路径获取音频，将路径保存到资源数组里面
     * @param path 路径
     * @param needCache 是否存入资源数组
     * @returns
     */
     public async getAudioClip(path: string, bundleId = '', needCache = true): Promise<cc.AudioClip> {
        let audioClip: cc.AudioClip = null;
        try {
            if (bundleId) {
                audioClip = await ResLoadMgr.Instance.loadBundleRes(bundleId, path);
            } else {
                audioClip = await ResLoadMgr.Instance.loadRes(path);
            }
        } catch (e) {
            console.error(`loadRes from ${path} error`);
            return null;
        }
        if (!(audioClip instanceof cc.AudioClip)) {
            console.error(`loadRes from ${path} error, not cc.AudioClip`);
            return null;
        }

        return audioClip;
    }

    public  BtnChildAddClickEvent(path: string, parentNode: cc.Node, callback: Function, target?: any, useCapture?: boolean, playAudio = true) {
        const childNode = path ? cc.find(path, parentNode) : parentNode;
        if (!childNode || !childNode.getComponent(cc.Button)) {
            console.error(`BtnChildAddClickEvent error: parent:${parentNode.name} path: ${path} no btn child`);
            return;
        }
        childNode.on(
            'click',
            button => {
                if (playAudio) {
                    // this.playMusicByResPath('music/CommonButton');
                }
                callback.call(target, button);
            },
            target,
            useCapture
        );
    }

    public  async loadTxt(path:string){
        const txt: cc.TextAsset = await ResLoadMgr.Instance.loadBundleRes('resources', path, cc.TextAsset);
        var textContent = txt.text;
        return textContent;
    }

    public  async loadJson(path:string){
        const data: cc.JsonAsset = await ResLoadMgr.Instance.loadBundleRes('resources', path, cc.JsonAsset);
        var jsonAsset = data.json;
        return jsonAsset;
    }

}
